<html>
<head>
<title>WebTag</title>

<script type="text/javascript">
	//if (navigator.userAgent != null && navigator.userAgent.indexOf("iPhone") != -1)
		window.location = "./i" + window.location.search;
</script>

<style type="text/css">
.tag { cursor: pointer; }
.needs_removal { color: red; }
.new { color: green; }

#tagPad div
{
	background: lightblue;
	height: 50px;
	width: 50px;
	cursor: pointer;
}

</style>

<script type="text/javascript" src="FlickrAjax.js"></script>
<script type="text/javascript" src="FlickrPhotoset.js"></script>
<script type="text/javascript" src="FlickrPhoto.js"></script>
<script type="text/javascript" src="flickr_misc.js"></script>

<script type="text/javascript">

var token = null;
var userId = null;

var queryStringParams = new Array();
queryStringParams['frob'] = null;

var queryString = window.location.search.substring(1);
var pairs = queryString.split('&');
for (var iPair = 0; iPair < pairs.length; iPair++) {
	var equalPos = pairs[iPair].indexOf('=');
	if (equalPos > 0) {
		var key = pairs[iPair].substring(0, equalPos);
		var value = pairs[iPair].substring(equalPos + 1);
		queryStringParams[key] = value;
	}
}


function getCookie(c_name)
{
	if (document.cookie.length == 0)
		return null;

	c_start = document.cookie.indexOf(c_name + "=");
	if (c_start != -1) {
		c_start = c_start + c_name.length + 1;
		c_end = document.cookie.indexOf(";", c_start);
		if (c_end == -1)
			c_end = document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
	}

	return null;
}

function setCookie(c_name, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	var cookieString = c_name + "=" + escape(value);
	if (expiredays != null)
		cookieString += ";expires=" + exdate.toGMTString();
	document.cookie = cookieString;
}


function retrieveToken()
{
	// verify token if it exists
	token = getCookie("token");
	if (token != null && token != "") {
		var response = getFromFlickrSynch("flickr.auth.checkToken", { }, false);
		if (response != null) {
			userId = response.auth.user.nsid;
			return;
		}
	}

	// reset token so new calls don't send old token
	token = "";
	setCookie("token", token);

	// redirect to auth page if we don't even have a frob
	var frob = queryStringParams['frob'];
	if (frob == null) {
		window.location = "auth.php";
		return;
	}

	// get token from frob
	var response = getFromFlickrSynch("flickr.auth.getToken", {"frob": frob});
	if (response == null)
		return;

	// record new token
	token = response.auth.token._content;
	setCookie("token", token);

	// welcome user and redirect to non-frob'd page
	window.alert("Welcome, " + response.auth.user.username + ".");
	window.location = "./";
}


function getTagsHtml(photo)
{
	var tags = photo.getTags();
	var tagNames = new Array();
	for (tag in tags)
		tagNames.push(tag);
	tagNames.sort();

	var returnVal = "";
	for (i in tagNames) {
		var tagName = tagNames[i];
		var tagStatus = tags[tagName];
		var tagStatusString = tagStatus == photo.NEEDS_REMOVAL ? "needs_removal"
			: tagStatus == photo.NEW ? "new" : "";
		returnVal += "<span class='tag " + tagStatusString + "' onclick='removeTag(\"" + tagName + "\")'>"
			+ tagName + "</span> ";
	}
	return returnVal;
}


function listSets(response)
{
	var listSetsButton = document.photosetForm.listSetsButton;
	if (response == null) {
		listSetsButton.value = "Retrieving Sets...";
		listSetsButton.disabled = true;
		flickrAjaxManager.get("flickr.photosets.getList", {"user_id": userId}, listSets);
	}
	else {
		listSetsButton.value = "Sets Retrieved";
		var photosetSelect = document.photosetForm.photosetSelect;
		while (photosetSelect.length > 0)
			photosetSelect.remove(0);
		for (i in response.photosets.photoset) {
			var photoset = response.photosets.photoset[i];
			var newOption = document.createElement("option");
			newOption.value = photoset.id;
			newOption.text = photoset.title._content;
			photosetSelect.add(newOption, null);
		}
	}
}


var photoset = null;
function showFirstPhoto()
{
	document.photosetForm.photosetSelect.blur(); // make sure arrow keys don't mess up our selection

	var selectedIndex = document.photosetForm.photosetSelect.selectedIndex;
	var photosetId = document.photosetForm.photosetSelect.options[selectedIndex].value;
	photoset = new FlickrPhotoset(photosetId, flickrAjaxManager);

	showNextPhoto();
}


var allowShowPrevPhoto = true;
function showPrevPhoto(photo)
{
	if (!photoset)
		return;

	applyTags();

	if (photo == null) {
		if (!allowShowPrevPhoto)
			return;
		allowShowPrevPhoto = false;
		setTimeout(function() { allowShowPrevPhoto = true; }, 250);

		photoset.callbackPrevPhoto(showPrevPhoto);
		return;
	}

	document.getElementById("photoLink").href = "http://flickr.com/photos/altruic/" + photo.getId();
	document.getElementById("photoImg").src = photo.getUrl();
	refreshTags();
}


var allowShowNextPhoto = true;
function showNextPhoto(photo)
{
	if (!photoset)
		return;

	// Even though we apply tags before requesting next photo, the tags could change before the next photo comes back.
	// We call applyTags before checking which status this function is in to capture that change.
	applyTags();

	if (photo == null) {
		if (!allowShowNextPhoto)
			return;
		allowShowNextPhoto = false;
		setTimeout(function() { allowShowNextPhoto = true; }, 250);

		photoset.callbackNextPhoto(showNextPhoto);
		return;
	}

	document.getElementById("photoLink").href = "http://flickr.com/photos/altruic/" + photo.getId();
	document.getElementById("photoImg").src = photo.getUrl();
	refreshTags();
}


function applyTags()
{
	var photo = photoset.getCurrentPhoto();
	if (photo == null)
		return;

	photo.applyTags();
	refreshTags();
}


function refreshTags()
{
	document.getElementById("tagsSpan").innerHTML = getTagsHtml(photoset.getCurrentPhoto());
}


function removeTag(tag)
{
	photoset.getCurrentPhoto().removeTag(tag);
	refreshTags();
}


function addTag(tag)
{
	photoset.getCurrentPhoto().addTag(tag);
	refreshTags();
}


// fixme: ESC should cancel out of naming mode
// fixme: need to trim/modify tags before they go into buttons
var padBeingEdited = null;
function padClicked(pad)
{
	var tag = pad.innerHTML;
	if (tag != undefined && tag != "") {
		addTag(tag)
		return;
	}

	padBeingEdited = pad;
	window.onkeydown = null;
	document.newTagForm.style.display = "inline";
	document.newTagForm.newTagEdit.focus();
}


function tagNamed()
{
	if (padBeingEdited != null) {
		var newTagEdit = document.newTagForm.newTagEdit;
		// fixme: adjust name to something in current tag cloud (proper capitalization, tab-completion?)
		padBeingEdited.innerHTML = newTagEdit.value;
		newTagEdit.value = "";
	}

	window.onkeydown = onKeyDown;
	document.newTagForm.style.display = "none";
	padBeingEdited = null;
}


// fixme: figure out how to support iphone google images swipe-browsing
function onKeyDown(event)
{
	switch (event.keyCode) {
		case 37 : // left arrow
		case 96 : // numpad 0
			showPrevPhoto();
			break;
		case 39 : // right arrow
		case 13 : // enter
			showNextPhoto();
			break;
		case 189 : // minus/underscore key
		case 109 : // numpad minus
			window.alert("tag removal mode would begin now (if coded)");
			break;
		case 187 : // equal/plus key
		case 107 : // numpad plus
			window.alert("tag addition mode would begin now (if coded)");
			break;
	}
}


window.onkeydown = onKeyDown;


function refreshStats()
	{ document.getElementById("managerStats").innerHTML = flickrAjaxManager.getRequestCount() + " request(s)"; }

	
var flickrAjaxManager = new FlickrAjaxManager();	
flickrAjaxManager.onupdated = refreshStats;


</script>

</head>
<body onload="retrieveToken()">

<form name="photosetForm">
<input type="button" name="listSetsButton" onclick="listSets()" value="List Sets" />
<select name="photosetSelect" onchange="showFirstPhoto()">
</select>
</form>

<div>
<span style="cursor:pointer" onclick="showPrevPhoto()">&lt;&lt; Prev</span> |
<span id="managerStats">0 request(s)</span> |
<span style="cursor:pointer" onclick="showNextPhoto()">Next &gt;&gt;</span>

</div>
<div id="tagsSpan"></div>
<a id="photoLink" target="_new"><img id="photoImg"/></a>

<table id="tagPad">
<tr>
	<td><div id="pad7" onclick="padClicked(this)"></div></td>
	<td><div id="pad8" onclick="padClicked(this)"></div></td>
	<td><div id="pad9" onclick="padClicked(this)"></div></td>
</tr>
<tr>
	<td><div id="pad4" onclick="padClicked(this)"></div></td>
	<td><div id="pad5" onclick="padClicked(this)"></div></td>
	<td><div id="pad6" onclick="padClicked(this)"></div></td>
</tr>
<tr>
	<td><div id="pad1" onclick="padClicked(this)"></div></td>
	<td><div id="pad2" onclick="padClicked(this)"></div></td>
	<td><div id="pad3" onclick="padClicked(this)"></div></td>
</tr>
</table>
<form name="newTagForm" style="display:none" onsubmit="tagNamed(); return false;"><input name="newTagEdit"/></form>


</body>
